import axios, { AxiosInstance } from 'axios';
import { notification, Spin } from 'antd';
import ReactDOM from 'react-dom/client';
import { getRandomString } from '@/utils/utils';
import { StorageKey } from '@/types/global';

// 当前请求数量
let httpCount: number = 0;
const showLoading = () => {
	if (httpCount === 0) {
		let dom = document.createElement('div');
		dom.setAttribute('id', 'app-fullsreen-loading');
		document.body.appendChild(dom);
		ReactDOM.createRoot(document.getElementById('app-fullsreen-loading')!).render(<Spin fullscreen />);
	}
	httpCount++;
};
const hideLoading = () => {
	httpCount--;
	if (httpCount === 0) {
		document.body.removeChild(document.getElementById('app-fullsreen-loading') as Node);
	}
};

export class Http {
	public static request: AxiosInstance;
	public static loading: any;
	public static shadeNum: number = 0;

	public static init() {
		// 创建axios实例
		this.request = axios.create({
			baseURL: import.meta.env.VITE_BASE_API_URL,
			timeout: 5 * 60 * 1000, // 请求 5分钟 超时
			headers: {
				'Content-Type': 'application/json',
			},
		});
		// 初始化拦截器
		this.initInterceptors();
		return axios;
	}

	public static initInterceptors() {
		// const authorization: string = 'Bearer ' + this.getToken()
		// 设置post请求头
		this.request.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
		// authorization && (this.request.defaults.headers.common['Authorization'] = authorization)
		/**
		 * 请求拦截器
		 * 每次请求前，如果存在token则在请求头中携带token
		 */
		this.request.interceptors.request.use(
			(config: any) => {
				const loading: boolean = config.loading ?? true;
				if(loading) {
					showLoading();
				}

				const token = sessionStorage.getItem(StorageKey.TOKEN);
				if(token) {
					config.headers.Authorization = `${token}`;
				}

				if(config.params && !config.params.uid) {
				    config.params.uid = getRandomString();
				} else if(config.data && !config.data.uid) {
				    config.data.uid = getRandomString();
				}

				return config;
			},
			(error: any) => {
				return Promise.reject(error);
			}
		);

		// 响应拦截器
		this.request.interceptors.response.use(
			(response: any) => {
				// 2 开头的状态码都会触发该函数
				hideLoading();
				return response.data;
			},
			(error: any) => {
				hideLoading();
				// 非 2 开头的状态码都会触发该函数
				if (error.response) {
					switch (error.response.status) {
						case 401:
							notification['error']({
								message: '403 连接失败',
							});
							break;
						case 403:
							notification['error']({
								message: '403 连接失败',
							});
							break;
						case 404:
							notification['error']({
								message: '404 连接失败',
							});
							break;
						case 500:
							notification['error']({
								message: '500 连接失败',
							});
							break;
					}
				}
				return Promise.reject(error);
			}
		);
	}
}

